<template>
    <view class="container">
        <!-- 顶部标题栏（保持不变） -->
        <view class="header">
            <text class="title">第 {{ roundNumber }} 局结算</text>
            <view class="divider"></view>
        </view>

        <!-- 加载状态（保持不变） -->
        <view v-if="loading" class="loading-state">...</view>
        
        <!-- 错误提示（保持不变） -->
        <view v-if="error" class="error-state">...</view>

        <!-- 主要内容区域 -->
        <view v-if="!loading && !error" class="content">
            <!-- 新增全局状态提示条 -->
            <view class="global-status" :class="globalStatus.type">
                <text>{{ globalStatus.text }}</text>
                <text v-if="globalStatus.progress" class="progress">{{ globalStatus.progress }}</text>
            </view>
            
            <!-- 玩家卡片列表 -->
            <view class="player-cards">
                <view 
                    v-for="player in players" 
                    :key="player.userId" 
                    class="player-card"
                    :class="{
                        'current-user': player.userId === currentUserId,
                        'submitted': submissionStatus[player.userId]
                    }"
                >
                    <!-- 玩家头像和信息 -->
                    <view class="player-info">
                        <image :src="player.avatar || defaultAvatar" class="avatar"></image>
                        <view class="info-text">
                            <text class="player-name">{{ player.nickname }}</text>
                            <text v-if="player.isWinner" class="winner-tag"> 赢家</text>
                        </view>
                        <!-- 提交状态标识 -->
                        <view class="status-badge" :class="getPlayerStatus(player.userId)">
                            {{ getStatusIcon(player.userId) }}
                        </view>
                    </view>
                    
                    <!-- 分数输入区域 -->
                    <view class="score-section">
                        <text class="score-label">得分：</text>
                        <input 
                            type="number" 
                            v-model="player.score" 
                            class="score-input"
                            @focus="clearIfDefault(player)"
                            @blur="restoreDefault(player)"
                            @input="validateScore(player)"
                            :disabled="shouldDisableInput(player)"
                        />
                    </view>
                    
                    <!-- 赢家选择（仅当前用户可见） -->
                    <view 
                        class="winner-section" 
                        v-if="player.userId === currentUserId"
                    >
                        <text class="winner-label">设为赢家：</text>
                        <switch 
                            :checked="player.isWinner" 
                            @change="handleWinnerChange(player.userId, $event.detail.value)"
                            color="#07C160"
                            :disabled="hasSubmitted"
                        />
                    </view>
                </view>
            </view>
            
            <!-- 结算说明 -->
            <view class="settlement-notice">
                <text> 所有玩家提交分数后系统将自动结算</text>
                <text v-if="remainingTime > 0" class="time-remaining">
                    ⏳ 剩余提交时间：{{ formatTime(remainingTime) }}
                </text>
            </view>
            
            <!-- 底部操作栏 -->
            <view class="action-bar">
                <button 
                    class="btn cancel-btn"
                    @click="handleCancel"
                    :disabled="isSubmitting"
                >
                    取消
                </button>
                
                <button 
                    class="btn submit-btn"
                    :class="submitBtnStatus"
                    @click="handleSubmit"
                    :disabled="shouldDisableSubmit"
                >
                    <view class="btn-content">
                        <text v-if="isSubmitting" class="loading-icon">⏳</text>
                        <text>{{ submitBtnText }}</text>
                    </view>
                </button>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted ,watch} from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useSocketStore } from '@/stores/modules/socketStore';

// 默认头像
const defaultAvatar = 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png';

// 状态管理
const socketStore = useSocketStore();
const { connectionState, roomData } = storeToRefs(socketStore);

// 响应式数据
const loading = ref(true);
const error = ref(null);
const isSubmitting = ref(false);
const roundNumber = ref(0);
const players = ref([]);
const roomId = ref('');
const currentUserId = ref('');

// 多人协同提交状态
const submissionStatus = ref({});
const finalSubmitTriggered = ref(false);
const remainingTime = ref(180); // 3分钟倒计时(秒)
const countdownInterval = ref(null);

// 计算当前玩家
const currentPlayer = computed(() => 
  players.value.find(p => p.userId === currentUserId.value) || {}
);

// 计算已提交玩家数量
const submittedCount = computed(() => 
  Object.values(submissionStatus.value).filter(Boolean).length
);

// 当前用户是否已提交
const hasSubmitted = computed(() => 
  submissionStatus.value[currentUserId.value]
);

// 是否所有玩家都已提交
const allSubmitted = computed(() =>
  players.value.length > 0 && 
  players.value.every(p => submissionStatus.value[p.userId])
);

// 是否所有分数已填写
const allScoresFilled = computed(() => {
  return players.value.every(player => {
    const score = parseInt(player.score);
    return player.score !== '' && !isNaN(score) && score >= 0;
  });
});

// 是否有赢家
const hasWinner = computed(() => {
  return players.value.some(p => p.isWinner);
});

// 全局状态提示
const globalStatus = computed(() => {
  if (allSubmitted.value) {
    return {
      type: 'success',
      text: '所有玩家已提交，正在结算中...',
      progress: ''
    };
  }
  
  if (hasSubmitted.value) {
    return {
      type: 'warning',
      text: '已提交，等待其他玩家',
      progress: `(${submittedCount.value}/${players.value.length})`
    };
  }
  
  return {
    type: 'info',
    text: '请填写分数并提交',
    progress: ''
  };
});

// 初始化数据
const initData = async () => {
  try {
    loading.value = true;
    error.value = null;
    submissionStatus.value = {};
    
    // 获取当前用户ID
    const userStr = uni.getStorageSync('user') || '{}';
    const user = JSON.parse(userStr);
    currentUserId.value = user.userinfo?.userid || '';
    
    // 获取房间数据
    const currentRoomData = roomData.value[roomId.value];
    if (!currentRoomData || !currentRoomData.members) {
      throw new Error('房间数据不存在，请重新进入房间');
    }
    
    // 初始化玩家数据
    players.value = Object.values(currentRoomData.members).map(member => ({
      userId: member.user_id,
      nickname: member.nickname,
      avatar: member.avatar,
      score: "0",
      isWinner: false
    }));
    
    // 初始化提交状态
    players.value.forEach(p => {
      submissionStatus.value[p.userId] = false;
    });
    
    // 注册Socket监听
    registerSocketListeners();
    
  } catch (err) {
    error.value = err.message || '加载数据失败，请稍后重试';
    console.error('初始化数据出错:', err);
  } finally {
    loading.value = false;
  }
};

// 注册Socket事件监听
const registerSocketListeners = () => {
  // 玩家提交事件
  socketStore.on('player_submitted', (data) => {
    if (data.room_id !== roomId.value || data.roundNumber !== roundNumber.value) return;
    
    // 更新提交状态
    submissionStatus.value[data.user_id] = true;
    
    // 同步其他玩家的分数数据
    if (data.user_id !== currentUserId.value) {
      const player = players.value.find(p => p.userId === data.user_id);
      if (player) {
        player.score = data.score.toString();
        player.isWinner = data.isWinner;
      }
    }
  });
  
  // 最终提交触发
  socketStore.on('final_submit_trigger', () => {
    if (!finalSubmitTriggered.value && allSubmitted.value) {
      finalSubmitTriggered.value = true;
      realSubmitToBackend();
    }
  });
  
  // 超时提醒
  socketStore.on('submit_timeout', () => {
    uni.showToast({ 
      title: `有${players.value.length - submittedCount.value}位玩家未提交`, 
      icon: 'none' 
    });
  });
  
  // 结算完成
  socketStore.on('settlement_completed', () => {
    uni.showToast({ title: '本局结算已完成' });
    setTimeout(() => uni.navigateBack(), 1500);
  });
};

// 分数验证
const validateScore = (player) => {
  // 只允许数字
  player.score = player.score.replace(/[^\d]/g, '');
  
  // 空值处理
  if (player.score === '') player.score = '0';
  
  // 最大值限制
  const num = parseInt(player.score);
  if (num > 500) player.score = '500';
};

// 输入框焦点处理
const clearIfDefault = (player) => {
  if (player.score === "0") player.score = "";
};

// 输入框失去焦点处理
const restoreDefault = (player) => {
  if (player.score === "") player.score = "0";
};

// 赢家状态变更
const handleWinnerChange = (userId, isWinner) => {
  if (userId !== currentUserId.value) return;
  
  // 只能设置自己为赢家
  const player = players.value.find(p => p.userId === userId);
  if (!player) return;
  
  // 取消其他玩家的赢家状态
  if (isWinner) {
    players.value.forEach(p => {
      p.isWinner = p.userId === userId;
    });
  }
  
  player.isWinner = isWinner;
  
  // 赢家自动设置默认分数
  if (isWinner) {
    player.score = "20";
  }
};

// 开始倒计时
const startCountdown = () => {
  clearInterval(countdownInterval.value);
  remainingTime.value = 180;
  
  countdownInterval.value = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
    } else {
      clearInterval(countdownInterval.value);
      handleTimeout();
    }
  }, 1000);
};

// 超时处理
const handleTimeout = () => {
  socketStore.emit('submit_timeout', {
    room_id: roomId.value,
    roundNumber: roundNumber.value
  });
};

// 格式化时间显示
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
};

// 提交处理
const handleSubmit = async () => {
  if (isSubmitting.value || !allScoresFilled.value || !hasWinner.value || hasSubmitted.value) {
    return;
  }
  
  isSubmitting.value = true;
  
  try {
    // 标记自己已提交
    submissionStatus.value[currentUserId.value] = true;
    
    // 广播提交事件
    await socketStore.emit('player_submitted', {
      room_id: roomId.value,
      roundNumber: roundNumber.value,
      user_id: currentUserId.value,
      score: currentPlayer.value.score,
      isWinner: currentPlayer.value.isWinner
    });

    // 如果是最后一个提交者
    if (allSubmitted.value) {
      await triggerFinalSubmit();
    }
  } catch (err) {
    console.error('提交失败:', err);
    submissionStatus.value[currentUserId.value] = false;
    uni.showToast({ title: '提交失败，请重试', icon: 'none' });
  } finally {
    isSubmitting.value = false;
  }
};

// 触发最终提交
const triggerFinalSubmit = async () => {
  await socketStore.emit('final_submit_trigger', {
    room_id: roomId.value,
    roundNumber: roundNumber.value
  });
};

// 实际提交到后端
const realSubmitToBackend = async () => {
  if (finalSubmitTriggered.value) return;
  finalSubmitTriggered.value = true;
  
  try {
    const submitData = {
      roomId: roomId.value,
      roundNumber: roundNumber.value,
      players: players.value.map(p => ({
        userId: p.userId,
        score: parseInt(p.score),
        isWinner: p.isWinner
      }))
    };
    
    // 实际API调用
    const res = await uni.request({
      url: 'http://172.16.24.120:5000/mysqlroom/rounds/settle',
      method: 'POST',
      data: submitData
    });
    
    if (res.statusCode === 200) {
      socketStore.emit('settlement_completed', {
        room_id: roomId.value,
        roundNumber: roundNumber.value
      });
    } else {
      throw new Error(res.data?.message || '提交失败');
    }
  } catch (err) {
    console.error('结算提交失败:', err);
    uni.showToast({ 
      title: err.message || '结算失败', 
      icon: 'none' 
    });
  }
};

// 取消操作
const handleCancel = () => {
  if (isSubmitting.value) return;
  uni.navigateBack();
};

// 玩家状态标识
const getPlayerStatus = (userId) => {
  if (!submissionStatus.value[userId]) return 'pending';
  if (userId === currentUserId.value) return 'self-submitted';
  return 'others-submitted';
};

// 状态图标
const getStatusIcon = (userId) => {
  const status = getPlayerStatus(userId);
  return {
    'pending': '',
    'self-submitted': '✅',
    'others-submitted': '☑️'
  }[status];
};

// 输入框禁用判断
const shouldDisableInput = (player) => {
  return player.userId !== currentUserId.value || 
         hasSubmitted.value || 
         isSubmitting.value;
};

// 提交按钮状态
const submitBtnStatus = computed(() => {
  if (isSubmitting.value) return 'submitting';
  if (hasSubmitted.value) return 'submitted';
  return 'ready';
});

// 提交按钮文本
const submitBtnText = computed(() => {
  if (isSubmitting.value) return '提交中...';
  if (hasSubmitted.value) return `等待中 (${submittedCount.value}/${players.value.length})`;
  return '提交分数';
});

// 提交按钮禁用判断
const shouldDisableSubmit = computed(() => {
  return isSubmitting.value || 
         !allScoresFilled.value || 
         !hasWinner.value || 
         hasSubmitted.value;
});

// 页面加载
onLoad((options) => {
  roomId.value = options.roomId;
  roundNumber.value = parseInt(options.roundNumber) || 0;
  
  if (connectionState.value !== 'connected' || !socketStore.isConnectedToRoom(roomId.value)) {
    socketStore.connect(roomId.value).then(() => {
      initData();
      startCountdown();
    });
  } else {
    initData();
    startCountdown();
  }
});

// 组件卸载清理
onUnmounted(() => {
  // 清理Socket监听
  socketStore.off('player_submitted');
  socketStore.off('final_submit_trigger');
  socketStore.off('submit_timeout');
  socketStore.off('settlement_completed');
  
  // 清理计时器
  clearInterval(countdownInterval.value);
});

// 监听Socket连接状态
watch(connectionState, (newState) => {
  if (newState === 'disconnected' && !loading.value && !error.value) {
    error.value = '连接已断开，请返回重新进入房间';
  }
});
</script>

<style scoped>
/* 全局容器样式 */
.container {
  padding: 0;
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.header {
  padding: 20px 16px 12px;
  background-color: #ffffff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  text-align: center;
  display: block;
}

.divider {
  height: 1px;
  background-color: #eee;
  margin-top: 12px;
}

/* 加载状态 */
.loading-state {
  padding: 40px 0;
  display: flex;
  justify-content: center;
}

/* 错误状态 */
.error-state {
  padding: 40px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.error-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 16px;
}

.error-text {
  font-size: 16px;
  color: #ff4d4f;
  margin-bottom: 20px;
  text-align: center;
}

.retry-button {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 8px 24px;
  font-size: 14px;
}

/* 全局状态提示条 */
.global-status {
  padding: 12px 16px;
  margin: 10px 16px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.global-status.info {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.global-status.warning {
  background-color: #fffbe6;
  color: #faad14;
  border: 1px solid #ffe58f;
}

.global-status.success {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.progress {
  font-weight: bold;
  font-size: 13px;
}

/* 玩家卡片容器 */
.player-cards {
  padding: 0 16px;
  margin-bottom: 20px;
}

.player-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.player-card.current-user {
  border-left: 4px solid #1890ff;
  background-color: #f0f9ff;
}

.player-card.submitted {
  opacity: 0.85;
}

/* 玩家信息区域 */
.player-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  background-color: #eee;
}

.info-text {
  flex: 1;
}

.player-name {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 4px;
}

.winner-tag {
  font-size: 12px;
  color: #07C160;
  display: inline-block;
  padding: 2px 6px;
  background-color: rgba(7, 193, 96, 0.1);
  border-radius: 4px;
}

/* 状态角标 */
.status-badge {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

/* 分数输入区域 */
.score-section {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.score-label {
  font-size: 14px;
  color: #666;
  width: 60px;
}

.score-input {
  flex: 1;
  height: 36px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 10px;
  font-size: 16px;
  color: #333;
}

.score-input:disabled {
  background-color: #f5f5f5;
  color: #999;
}

/* 赢家选择区域 */
.winner-section {
  display: flex;
  align-items: center;
}

.winner-label {
  font-size: 14px;
  color: #666;
  width: 60px;
}

/* 结算说明 */
.settlement-notice {
  padding: 12px 16px;
  margin: 0 16px 20px;
  background-color: #f6f6f6;
  border-radius: 8px;
  font-size: 13px;
  color: #666;
}

.settlement-notice text {
  display: block;
}

.time-remaining {
  margin-top: 6px;
  color: #faad14;
  font-weight: 500;
}

/* 底部操作栏 */
.action-bar {
  display: flex;
  padding: 16px;
  background-color: #fff;
  border-top: 1px solid #eee;
  position: sticky;
  bottom: 0;
  gap: 12px;
}

.btn {
  flex: 1;
  height: 48px;
  border-radius: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s;
  border: none;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.cancel-btn:active {
  background-color: #e5e5e5;
}

.submit-btn {
  background-color: #07C160;
  color: white;
}

.submit-btn.submitted {
  background-color: #FF9500;
}

.submit-btn.submitting {
  background-color: #007AFF;
}

.submit-btn:disabled {
  opacity: 0.7;
}

.btn-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.loading-icon {
  animation: spin 1s linear infinite;
}

/* 动画效果 */
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.6; }
  100% { opacity: 1; }
}
</style>